package com.freesky.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;

import com.alipay.api.request.AlipayUserDtbankcustChannelvoucherSendRequest;
import com.alipay.api.response.AlipayUserDtbankcustChannelvoucherSendResponse;
import com.freesky.biz.activity.domain.TAlipayCouponDetail;
import com.freesky.biz.activity.mapper.CouponDetailMapper;
import com.freesky.biz.citic.domain.TCiticLucky;
import com.freesky.biz.citic.mapper.CiticLuckyMapper;
import com.freesky.biz.citic.service.CiticSendService;
import com.freesky.biz.external.service.MobileChengService;
import com.freesky.biz.external.service.MobileJulivesService;
import com.freesky.biz.external.service.MobileRechargeBlueService;
import com.freesky.biz.pay.config.AliPayConfiguration;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("citicLuckyTask")
public class CiticLuckyTask {

    private static final Logger logger = LoggerFactory.getLogger(CiticLuckyTask.class);

    @Autowired
    private CiticLuckyMapper citicLuckyMapper;

    @Autowired
    private CouponDetailMapper couponDetailMapper;

    @Autowired
    private MobileRechargeBlueService mobileRechargeBlueService;

    @Autowired
    private MobileJulivesService mobileJulivesService;

    @Autowired
    private MobileChengService mobileChengService;

    @Autowired
    private CiticSendService citicSendService;

    @Autowired
    private AliPayConfiguration aliPayConfiguration;

    /**
     * 信运抢券的任务处理
     *
     */
    public void taskProcess() {
        logger.info("citicLuckyTask task start");
        List<TCiticLucky> citicLuckyList = citicLuckyMapper.selectUnProcessList();
        for(TCiticLucky citicLucky : citicLuckyList){
            if("1".equalsIgnoreCase(citicLucky.getFavourFlag())) {
                int nCount = citicLuckyMapper.getReceiveCount(citicLucky.getCustId());
                if (nCount > 0) {
                    citicRefund(citicLucky, "退款：已享受优惠!");
                    continue;
                }
            }

            //发放类型，5001、微信立减金，5002支付宝红包，5003话费充值
            if("5002".equalsIgnoreCase(citicLucky.getType())){
                grantAlipayCoupon(citicLucky);
            } else if("5003".equalsIgnoreCase(citicLucky.getType())){
                if (StringUtils.isEmpty(citicLucky.getChannel())) {
                    sendMobileRechargeBlue(citicLucky);
                } else if ("蓝色".equalsIgnoreCase(citicLucky.getChannel())) {
                    sendMobileRechargeJulive(citicLucky);
                } else {
                    sendMobileRechargeCheng(citicLucky);
                }
            }
        }
    }

    //蓝色
    public void sendMobileRechargeBlue(TCiticLucky citicLucky){
        try{
            citicLucky.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileRechargeBlueService.sendMobileRecharge(
                    "CITIC_" + citicLucky.getLastReqId(),
                    String.valueOf(citicLucky.getAmt()),
                    citicLucky.getMobile());

            citicLucky.setChannel("蓝色");
            citicLucky.setRespCode(result.get("code").toString());
            citicLucky.setRespMsg(result.getMsg());

            if(result.isSuccess()){
                citicLucky.setProcessed("2");
                citicLucky.setRechargeId(result.get("data").toString());
            } else {
                citicLucky.setProcessed("3");
            }
            citicLuckyMapper.updateProcessedResultById(citicLucky);

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-蓝色接口",ioe.getMessage());
        }
    }

    public void sendMobileRechargeJulive(TCiticLucky citicLucky){
        try{
            citicLucky.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileJulivesService.sendMobileRecharge(
                    "CITIC_" + citicLucky.getLastReqId(),
                    String.valueOf(citicLucky.getAmt()),
                    citicLucky.getMobile());

            citicLucky.setChannel("智信");
            citicLucky.setRespCode(result.get("code").toString());
            citicLucky.setRespMsg(result.getMsg());

            if(result.isSuccess()){
                citicLucky.setRechargeId(result.get("data").toString());
                citicLucky.setProcessed("2");
            } else {
                citicLucky.setProcessed("3");
            }
            citicLuckyMapper.updateProcessedResultById(citicLucky);
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-智信接口",ioe.getMessage());
        }
    }

    public void sendMobileRechargeCheng(TCiticLucky citicLucky){
        try{
            citicLucky.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileChengService.sendMobileRecharge(
                    "CITIC_" + citicLucky.getLastReqId(),
                    String.valueOf(citicLucky.getAmt()),
                    citicLucky.getMobile());
            citicLucky.setChannel("橙券");
            citicLucky.setRespCode(result.get("code").toString());
            citicLucky.setRespMsg(result.getMsg());

            if(result.isSuccess()){
                citicLucky.setRechargeId("");
                citicLucky.setProcessed("2");
            } else {
                citicLucky.setProcessed("3");
            }
            citicLuckyMapper.updateProcessedResultById(citicLucky);
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-智信接口",ioe.getMessage());
        }
    }

    //支付宝通用红包
    public void grantAlipayCoupon(TCiticLucky citicLucky){
        try{
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            certAlipayRequest.setServerUrl(aliPayConfiguration.getGatewayUrl());
            certAlipayRequest.setAppId(aliPayConfiguration.getAppId());
            certAlipayRequest.setPrivateKey(aliPayConfiguration.getPrivateKey());
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset(aliPayConfiguration.getCharset());
            certAlipayRequest.setSignType(aliPayConfiguration.getSignType());
            certAlipayRequest.setCertPath(aliPayConfiguration.getAppCertPath());
            certAlipayRequest.setAlipayPublicCertPath(aliPayConfiguration.getAlipayCertPath());
            certAlipayRequest.setRootCertPath(aliPayConfiguration.getAlipayRootCertPath());
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

            AlipayUserDtbankcustChannelvoucherSendRequest request = new AlipayUserDtbankcustChannelvoucherSendRequest();

            request.setBizContent("{" +
                    "  \"phone_id\":\"" + citicLucky.getMobile() + "\"," +
                    "  \"activity_id\":\"ACT690CCV01800770\"," +
                    "  \"out_biz_no\":\"" + citicLucky.getId() + "\"" +
                    "}");

            // 支付宝通用红包Resp:{"activityId":"ACT190CCV00515644","activityOrderId":"20220324180321ACT09393CCV00051406428","body":"{\"alipay_user_dtbankcust_channelvoucher_send_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"activity_id\":\"ACT190CCV00515644\",\"activity_order_id\":\"20220324180321ACT09393CCV00051406428\",\"discount_threshold_amt\":1001,\"discount_type\":\"reduce\",\"discount_value\":1000,\"send_amount\":1000,\"send_status\":\"SUCCESS\",\"voucher_id\":\"202203240007300293240AZCWK1F\"},\"alipay_cert_sn\":\"a7456c1d07b0d38c65d5de409b519d6b\",\"sign\":\"Mp/agpDS5+HUChJcnUnGfiKJb970ydZYNFseFji2FhFAbRFIesJIMXwnaDnBI8vSzRlQjf7GRRDTPYJlWehVmD/XrPNpbSqJK0kmi8OGgBO9vAA8vI7liq8NkenOa7wEe1RqTzjiHIRI4BHoGOPTQiugOLoUpG9vQztcso6eQXr+gCBZkBcqi0GXVbr7137aZcYQ94juZI7UjES0GYOEUbjXq2gBik8cawpT0iTkWfQk1IwHQKQ5bcjC1L4eh11LMwbyHG4zXzJo1ZUnnbIH3NqemYSTtGqcYmpBfta7wkIw7O201NnogNywX6QJ3Ry9EJMJ3BsCR2ENZYhBoIhqqQ==\"}","code":"10000","discountThresholdAmt":1001,"discountType":"reduce","discountValue":1000,"errorCode":"10000","msg":"Success","params":{"biz_content":"{  \"user_id\":\"2088512933424935\",  \"activity_id\":\"ACT190CCV00515644\",  \"out_biz_no\":\"956578649744740352\"}"},"sendAmount":1000,"sendStatus":"SUCCESS","success":true,"voucherId":"202203240007300293240AZCWK1F"}
            logger.info("支付宝通用红包Req:"+request.getBizContent());
            AlipayUserDtbankcustChannelvoucherSendResponse response = alipayClient.certificateExecute(request);
            logger.info("支付宝通用红包Resp:"+ JSON.toJSONString(response));

            if (response.isSuccess()){
                citicLucky.setChannel("支付宝");
                citicLucky.setRefundFlag("0");
                citicLucky.setRespMsg("已下发红包");
                citicLucky.setProcessed("4");

                citicLuckyMapper.updateProcessedResultById(citicLucky);

                TAlipayCouponDetail alipayCouponModel = new TAlipayCouponDetail();
                alipayCouponModel.setId(SeqUtil.getSeqId());
                alipayCouponModel.setAppId("");
                alipayCouponModel.setActivityId(response.getActivityId());
                alipayCouponModel.setActivityOrderId(response.getActivityOrderId());
                alipayCouponModel.setVoucherId(response.getVoucherId());
                alipayCouponModel.setAmt(citicLucky.getAmt());
                alipayCouponModel.setOpenId(citicLucky.getOpenId());
                alipayCouponModel.setBusiId(citicLucky.getId());
                alipayCouponModel.setStatus("");
                couponDetailMapper.addAliCouponDetail(alipayCouponModel);
            } else {
                citicLucky.setRespMsg("退款："+response.getSubMsg());
                citicRefund(citicLucky,citicLucky.getRespMsg());
            }

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-农行首绑有礼-grantAlipayCoupon",ioe.getMessage());
        }
    }

    //全付通退款
    public void citicRefund(TCiticLucky citicLucky,
                             String reason){
        try{
            citicLucky.setRefundFlag("1");
            citicLucky.setRefundNo(SeqUtil.getSeqId());
            citicLucky.setRespMsg(reason);

            //:{"RFUTRANJNLNO":"","RETMSG":"原支付订单信息不存在。","RETCODE":"XYRFD30","SETTLEDATE":"","PAYBANKNAME":"","UNDISCOUNTAMT":"","TRANENDDATE":"","DISCOUNTAMT":""}

            AjaxResult result = citicSendService.payRefund(citicLucky.getOrderNo(),citicLucky.getRefundNo(),
                    citicLucky.getPayAmt(),citicLucky.getPayAmt());
            if(result.isSuccess()){
                citicLucky.setProcessed("4");
                JSONObject jsonObject = JSON.parseObject(result.get("data").toString());
                citicLucky.setRespMsg(citicLucky.getRespMsg() + "||,全付通："+jsonObject.getString("RETMSG"));
            } else {
                citicLucky.setProcessed("3");
                citicLucky.setRespMsg(citicLucky.getRespMsg() +"||,全付通：" + result.getMsg());
            }
            citicLuckyMapper.updateRefundById(citicLucky);

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-农行首绑有礼-alipayRefund",ioe.getMessage());
        }
    }
}
